package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/go-gin-admin/util"
	"net/http"
)

// 权限检查中间件
func AuthCheckRole() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 解析token
		token := util.GetToken(c)
		if token == "" {
			c.JSON(http.StatusOK, new(util.Response).Err("授权被拒绝，请求中auth为空"))
			c.Abort()
			return
		}

		// 解析token
		myClaims, err := util.ParseToken(token)
		if err != nil {
			c.JSON(http.StatusOK, new(util.Response).Err("无效的token"))
			c.Abort()
			return
		}
		//if myClaims.RoleKeys[0] == "admin" {
		//	c.Next()
		//	return
		//}

		// 权限实例
		e, err := util.Casbin()
		if err != nil {
			c.JSON(http.StatusOK, new(util.Response).Err("您没有该接口权限"))
			c.Abort()
			return
		}
		enforce, err := e.Enforce(myClaims.RoleKeys[0], c.Request.URL.Path, c.Request.Method)
		if err != nil {
			return
		}
		// 权限通过
		if enforce {
			c.Next()
		} else {
			c.JSON(http.StatusOK, new(util.Response).Err("您没有该接口权限"))
			c.Abort()
			return
		}
	}
}
